package com.sinopec.basemodule.http.dns;

import com.alibaba.sdk.android.httpdns.HttpDns;
import com.alibaba.sdk.android.httpdns.HttpDnsService;
import com.sinopec.basemodule.BaseApplication;
import com.sinopec.basemodule.BuildConfig;
import com.sinopec.basemodule.common.Logger;
import com.sinopec.basemodule.http.api.RetroAPIFactory;

import org.jetbrains.annotations.NotNull;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Dns;

/**
 * 创建人：lwj<br/>
 * 创建时间：2019/12/6 10:07 <br/>
 */
public class OkHttpDns implements Dns {
    private static final Dns SYSTEM = Dns.SYSTEM;
    public HttpDnsService httpdns;//httpdns 解析服务
    private static OkHttpDns instance = null;

    private OkHttpDns() {
        this.httpdns = HttpDns.getService(BaseApplication.getInstance().getApplicationContext(), "124572", "1798b81be878486ed6284d21f19088bf");
        setPreResoveHosts();
        // 允许过期IP以实现懒加载策略
        this.httpdns.setExpiredIPEnabled(true);
        this.httpdns.setPreResolveAfterNetworkChanged(true);
        this.httpdns.setCachedIPEnabled(false);
    }

    /**
     * 设置预解析域名列表
     */
    private void setPreResoveHosts() {
        // 设置预解析域名列表
        // 可以替换成您在后台配置的域名
        String host1 = null;
        String host2 = null;
        try {
            host1 = new URL(RetroAPIFactory.BASEURL).getHost();
            host2 = new URL(BuildConfig.ImageUrl).getHost();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        httpdns.setPreResolveHosts(new ArrayList<>(Arrays.asList(host1, host2)));
        Logger.i("OkHttpDns", "设置预解析域名成功");
    }

    public static OkHttpDns getInstance() {
        if (instance == null) {
            instance = new OkHttpDns();
        }
        Logger.i("OkHttpDns", "初始化HTTP DNS");
        return instance;
    }

    @NotNull
    @Override
    public List<InetAddress> lookup(@NotNull String hostname) throws UnknownHostException {
        //通过异步解析接口获取ip
        Logger.i("OkHttpDns", "=====================通过异步解析接口获取ip========================" + hostname);
        String ip = httpdns.getIpByHostAsync(hostname);
        Logger.i("OkHttpDns", "获取到ip是否为null " + (ip == null));
        if (ip != null) {
            //如果ip不为null，直接使用该ip进行网络请求
            List<InetAddress> inetAddresses = Arrays.asList(InetAddress.getAllByName(ip));
            Logger.i("OkHttpDns", "inetAddresses:" + inetAddresses);
            Logger.i("OkHttpDns", "=====================通过异步解析接口获取ip  END========================");
            return inetAddresses;
        }
        Logger.i("OkHttpDns", "=====================通过异步解析接口获取ip  END========================");
        //如果返回null，走系统DNS服务解析域名
        return Dns.SYSTEM.lookup(hostname);
    }
}
